/*
Copyright 2021 LuJun

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished 
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

import {
    dragonBones,
    TTFFont,
    SpriteAtlas,
    LabelAtlas,
    Font,
    Mesh,
    AudioClip,
    Prefab,
    TextAsset,
    JsonAsset,
    Material,
    AnimationClip,
    PhysicsMaterial,
    TiledMapAsset,
    sp,
    VideoClip,
    TerrainAsset,
    ParticleAsset,
    Script,
    EffectAsset,
    ImageAsset,
    SceneAsset,
    BufferAsset,
    Skeleton,
    SpriteFrame,
    BitmapFont,
    Asset,
    AssetManager,
    error,
    resources,
    __private
} from 'cc';
import {
    loadAnimationClip,
    loadAudioClip,
    loadBitmapFont,
    loadBufferAsset,
    loadDragonBonesAsset,
    loadDragonBonesAtlasAsset,
    loadEffectAsset,
    loadFont,
    loadImageAsset,
    loadJsonAsset,
    loadLabelAtlas,
    loadMaterial,
    loadMesh,
    loadParticleAsset,
    loadPhysicsMaterial,
    loadPrefab,
    loadSceneAsset,
    loadScript,
    loadSkeleton,
    loadSkeletonData,
    loadSpriteAtlas,
    loadSpriteFrame,
    loadTerrainAsset,
    loadTextAsset,
    loadTiledMapAsset,
    loadTTFFont,
    loadVideoClip
} from './asset';
import { conflict } from './base';

const TAG = 'lcc/core/asset-loader.ts';

/**
 * @zh
 * 资源加载器函数
 */
export type AssetLoaderFunction = (path: string, bundle: AssetManager.Bundle) => Promise<any>;

/**
 * @zh
 * 资源加载器
 */
class AssetLoader {
    /**
     * @zh
     * 单例对象
     */
    private static _instance: AssetLoader = null!;

    /**
     * @zh
     * 获得单例对象
     */
    static get instance() {
        if (AssetLoader._instance === null) {
            AssetLoader._instance = new AssetLoader();
        }
        return AssetLoader._instance;
    }

    /**
     * 构造函数
     */
    private constructor() {}

    /**
     * 加载器映射表
     */
    private _loaderMap: { [key: string]: AssetLoaderFunction } = Object.create(null);

    /**
     * @zh
     * 注册资源加载器
     *
     * @param nameOrType 资源名称或者类型
     * @param loader 加载器
     */
    register<T extends Asset>(
        nameOrType: string | __private._cocos_core_asset_manager_shared__AssetType<T>,
        loader: AssetLoaderFunction
    ) {
        let name = typeof nameOrType !== 'string' ? nameOrType.name : nameOrType;
        if (this._loaderMap[name]) {
            conflict(TAG, `asset loader ${name} conflict`);
        }
        this._loaderMap[name] = loader;
    }

    /**
     * @zh
     * 加载资源
     *
     * @param nameOrType 资源名称或者类型
     * @param path 资源路径
     * @param bundle 可选，资源包，默认resources
     * @returns 资源对象
     */
    async load<T extends Asset>(
        nameOrType: string | __private._cocos_core_asset_manager_shared__AssetType<T>,
        path: string,
        bundle: AssetManager.Bundle = resources
    ) {
        let name = typeof nameOrType !== 'string' ? nameOrType.name : nameOrType;
        let loader = this._loaderMap[name];
        if (!loader) {
            error(TAG, `loader ${name} not found`);
            return null;
        }

        let result = await loader(path, bundle);

        return result as T;
    }
}

/**
 * @zh
 * 资源加载器对象
 */
export const assetLoader = AssetLoader.instance;

// 预设加载器
assetLoader.register(SpriteAtlas, loadSpriteAtlas);
assetLoader.register(TTFFont, loadTTFFont);
assetLoader.register(LabelAtlas, loadLabelAtlas);
assetLoader.register(BitmapFont, loadBitmapFont);
assetLoader.register(Font, loadFont);
assetLoader.register(SpriteFrame, loadSpriteFrame);
assetLoader.register(Mesh, loadMesh);
assetLoader.register(Skeleton, loadSkeleton);
assetLoader.register(AudioClip, loadAudioClip);
assetLoader.register(BufferAsset, loadBufferAsset);
assetLoader.register(Prefab, loadPrefab);
assetLoader.register(SceneAsset, loadSceneAsset);
assetLoader.register(TextAsset, loadTextAsset);
assetLoader.register(JsonAsset, loadJsonAsset);
assetLoader.register(ImageAsset, loadImageAsset);
assetLoader.register(EffectAsset, loadEffectAsset);
assetLoader.register(Material, loadMaterial);
assetLoader.register(Script, loadScript);
assetLoader.register(AnimationClip, loadAnimationClip);
assetLoader.register(ParticleAsset, loadParticleAsset);
assetLoader.register(PhysicsMaterial, loadPhysicsMaterial);
assetLoader.register(TerrainAsset, loadTerrainAsset);
assetLoader.register(TiledMapAsset, loadTiledMapAsset);
assetLoader.register(VideoClip, loadVideoClip);
assetLoader.register(dragonBones.DragonBonesAsset, loadDragonBonesAsset);
assetLoader.register(dragonBones.DragonBonesAtlasAsset, loadDragonBonesAtlasAsset);
assetLoader.register(sp.SkeletonData, loadSkeletonData);

// 加载器别名设置
assetLoader.register('ttf', loadTTFFont);
assetLoader.register('mp3', loadAudioClip);
assetLoader.register('jpg', loadImageAsset);
assetLoader.register('png', loadImageAsset);
assetLoader.register('txt', loadTextAsset);
assetLoader.register('json', loadJsonAsset);
assetLoader.register('mp4', loadVideoClip);
